package yannan.voiplock4ble;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yongchun.library.view.ImageSelectorActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LoggedBaseActivity;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.UserAccount;
import yannan.voiplock4ble.bean.UserBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.UserAccountDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.DeviceUtils;
import yannan.voiplock4ble.utils.PhotoViewUtils;
import yannan.voiplock4ble.utils.StringEncrypt;
import yannan.voiplock4ble.utils.ToastUtils;
import yannan.voiplock4ble.view.CircleImageView;

/**
 * 用户中心页面
 */
@Content(R.layout.activity_user_center)
public class UserCenterActivity extends LoggedBaseActivity {

    @Bind(R.id.img_user_center_back)
    ImageView imgUserCenterBack;
    @Bind(R.id.tv_user_center_complete)
    TextView tvUserCenterComplete;
    @Bind(R.id.line_input_userId)
    LinearLayout lineInputUserId;
    @Bind(R.id.ic_user_center_nickname)
    ImageView icUserCenterNickname;
    @Bind(R.id.et_user_center_nickname)
    TextView etUserCenterNickname;
    @Bind(R.id.line_input_nickname)
    LinearLayout lineInputNickname;
    @Bind(R.id.tv_user_center_phone)
    TextView tvUserCenterPhone;
    @Bind(R.id.view_divider)
    View viewDivider;
    @Bind(R.id.img_user_center_bg)
    ImageView imgUserCenterBg;
    @Bind(R.id.img_user_center_head)
    CircleImageView imgUserCenterHead;
    @Bind(R.id.btn_change_password)
    Button btnChangePassword;
    @Bind(R.id.et_original_password)
    EditText etOriginalPassword;
    @Bind(R.id.et_new_password)
    EditText etNewPassword;
    @Bind(R.id.et_confirm_password)
    EditText etConfirmPassword;
    @Bind(R.id.btn_password_complete)
    Button btnPasswordComplete;
    @Bind(R.id.frame_menu)
    LinearLayout frameMenu;
    @Bind(R.id.frame_content)
    RelativeLayout frameContent;
    @Bind(R.id.drawer)
    RelativeLayout drawer;

    private UserAccount userAccount;
    private boolean showMenu;

    @Override
    public void initData() {
//        MyApplication.getInterface().activityMap.put(this.getLocalClassName(), this);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        UserBean mUserBean = MyApplication.getInterface().userBean;
        if (mUserBean != null) {
            etUserCenterNickname.setHint(mUserBean.nickName);
            tvUserCenterPhone.setText(mUserBean.userAccount);
            NetUtils.loadCircleImage(mContext, imgUserCenterHead, R.drawable.ic_admin_head, NetUtils.Base_Url_Down + mUserBean.headImageUrl);
        }
    }

    @OnClick({R.id.img_user_center_head, R.id.img_user_center_back, R.id.tv_user_center_complete, R.id
            .btn_change_password, R.id.btn_password_complete, R.id.img_user_center_bg, R.id.frame_content})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.img_user_center_head:
                PhotoViewUtils.startPicture(this);
                break;
            case R.id.tv_user_center_complete:
                if (showMenu) {
                    showOrHidePage();
                } else {
                    MyApplication.getInterface().userBean.nickName = etUserCenterNickname.getText().toString();
                    changeNickName();
                }
                break;
            case R.id.img_user_center_back:
                backUp();
                break;
            case R.id.btn_change_password:
                showOrHidePage();
                break;
            case R.id.btn_password_complete:

                changePassword();
                break;
            //当显示密码界面的时候，点击左侧可以取消显示密码界面
            case R.id.img_user_center_bg:
            case R.id.frame_content:
                if (showMenu) {
                    showOrHidePage();
                }
                break;
        }
    }

    private void showOrHidePage() {
        TranslateAnimation animation = null;
        if (showMenu) {
            ObjectAnimator.ofFloat(frameContent, "translationX", 0)
                    .setDuration(1000).start();
            showMenu = false;
        } else {
            frameMenu.setMinimumWidth(DeviceUtils.getScreenWidth() * 70 / 100);
            ObjectAnimator.ofFloat(frameContent, "translationX", -DeviceUtils.getScreenWidth() * 70 / 100)
                    .setDuration(1000).start();
            showMenu = true;
        }
    }

    /**
     * 修改密码
     */
    private void changePassword() {
        showProgress();
        userAccount = DaoUtils.getDao(UserAccountDaoManager.class).selectFirst();
//   或者查询     List<UserAccount> ss = DaoUtils.getDao(UserAccountDaoManager.class).queryRaw("where USER_ACCOUNT = ? ", MyApplication.getInterface().userBean.userAccount);
        String userPwd = userAccount.userPwd;
        if (etOriginalPassword.getText().toString().equals("")) {
            ToastUtils.showToast(UserCenterActivity.this, "请输入原密码");
            etOriginalPassword.requestFocus();
            dimssProgress();
            return;
        }
        if (etNewPassword.getText().toString().equals("")) {
            ToastUtils.showToast(UserCenterActivity.this, "请输入新密码");
            etNewPassword.requestFocus();
            dimssProgress();
            return;
        }
        if (etConfirmPassword.getText().toString().equals("")) {
            ToastUtils.showToast(UserCenterActivity.this, "请确认新密码");
            etConfirmPassword.requestFocus();
            dimssProgress();
            return;
        }
        if (!userPwd.equals(StringEncrypt.EncryptBySHA_256(etOriginalPassword.getText().toString()))) {
            ToastUtils.showToast(UserCenterActivity.this, "请正确输入原密码");
            etOriginalPassword.requestFocus();
            dimssProgress();
            return;
        }
        if (!etNewPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
            ToastUtils.showToast(UserCenterActivity.this, "新密码不一致");
            dimssProgress();
            return;
        }
        NetUtils.getNetworkService().changePwd(StringEncrypt.EncryptBySHA_256(etNewPassword.getText().toString()), MyApplication.getInterface()
                .userBean.userId).enqueue(new NetworkCallBack<CommonResponse>() {
            @Override
            public void onSuc(CommonResponse resBody) {
                dimssProgress();
                showOrHidePage();
                ToastUtils.showToast(UserCenterActivity.this, "密码修改成功");
                userAccount.userPwd = StringEncrypt.EncryptBySHA_256(etNewPassword.getText().toString());
                DaoUtils.getDao(UserAccountDaoManager.class).update(userAccount);
                etConfirmPassword.setText("");
                etNewPassword.setText("");
                etOriginalPassword.setText("");
            }

            @Override
            public void onFail(String msg) {
                dimssProgress();
                ToastUtils.showToast(UserCenterActivity.this, "密码修改失败");
            }
        });
    }

    /**
     * 完成按钮
     */
    private void changeNickName() {
        showProgress();
        if (MyApplication.getInterface().userBean != null) {
            NetUtils.getNetworkService().uploadUserInfo(MyApplication.getInterface().userBean.userId, MyApplication.getInterface().userBean.nickName,
                    MyApplication.getInterface().userBean.headImageUrl).enqueue(new NetworkCallBack<CommonResponse>() {
                @Override
                public void onSuc(CommonResponse resBody) {
                    ToastUtils.showToast(UserCenterActivity.this, "个人资料修改成功");
                    if (!TextUtils.isEmpty(etUserCenterNickname.getText().toString())) {
                        MyApplication.getInterface().userBean.nickName = etUserCenterNickname.getText().toString();
                    }
                    EventBus.getDefault().post("changeNickName");
                    dimssProgress();
                }

                @Override
                public void onFail(String msg) {
                    dimssProgress();
                    ToastUtils.showToast(UserCenterActivity.this, "个人资料修改失败");
                }
            });
        }
    }

    //修改头像
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Object msg) {
        if (msg instanceof String) {
            if (msg.equals("updateHeadImg"))
                changeNickName();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            PhotoViewUtils.upLoadHead(UserCenterActivity.this, images.get(0).toString(), "", imgUserCenterHead);
        }
    }

    /**
     * 后退事件
     */
    private void backUp() {
//        PopShowUtils.showCommonDialog(mContext, "确定要退出吗？", "取消", "确定", true, new PopShowUtils.IDialogCommonListener() {
//            @Override
//            public void onClick(int dir) {
//                if (dir == PopShowUtils.COMMON_DIALOG_RIGHT)
//                    UserCenterActivity.this.finish();
//            }
//        });
        finish();
    }

    @Override
    public void onBackPressed() {
        backUp();
    }

}
